package com.stoa.floatlib.core

import android.view.MotionEvent
import android.view.View
import com.blankj.utilcode.util.SizeUtils
import kotlin.math.abs

internal class TouchProxy(private val mEventListener: OnTouchEventListener?) {
    private val MIN_DISTANCE_MOVE = 4
    private val MIN_TAP_TIME = 1000

    private var mLastX = 0
    private var mLastY = 0
    private var mStartX = 0
    private var mStartY = 0
    private var mState = TouchState.STATE_STOP
    private var isClick = false
    private var startTime = 0L
    private var endTime = 0L

    private enum class TouchState {
        STATE_MOVE, STATE_STOP
    }

    fun onTouchEvent(v: View, event: MotionEvent): Boolean {
        val distance: Int = SizeUtils.dp2px(1f) * MIN_DISTANCE_MOVE
        val x = event.rawX.toInt()
        val y = event.rawY.toInt()
        when (event.action) {
            MotionEvent.ACTION_DOWN -> {
                isClick = false
                startTime = System.currentTimeMillis()
                mStartX = x
                mStartY = y
                mLastY = y
                mLastX = x
                mEventListener?.onDown(x, y)
            }
            MotionEvent.ACTION_MOVE -> {
                isClick = true
                if (abs(x - mStartX) < distance
                    && abs(y - mStartY) < distance
                ) {
                    if (mState == TouchState.STATE_STOP) {
//                        break
                    }
                } else if (mState != TouchState.STATE_MOVE) {
                    mState = TouchState.STATE_MOVE
                }
                mEventListener?.onMove(mLastX, mLastY, x - mLastX, y - mLastY)
                mLastY = y
                mLastX = x
                mState = TouchState.STATE_MOVE
            }
            MotionEvent.ACTION_UP -> {
                endTime = System.currentTimeMillis()
                mEventListener?.onUp(x, y)
                if (mState != TouchState.STATE_MOVE
                    && event.eventTime - event.downTime < MIN_TAP_TIME
                ) {
                    v.performClick()
                }
                mState = TouchState.STATE_STOP
                isClick = (endTime - startTime) > 0.5 * 1000L
            }
            else -> {
            }
        }
        return true
    }


    interface OnTouchEventListener {
        fun onMove(x: Int, y: Int, dx: Int, dy: Int)
        fun onUp(x: Int, y: Int)
        fun onDown(x: Int, y: Int)
    }
}